﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using PMRC.API.Helper;
using PMRC.API.Hubs;
using PMRC.API.Model.WeChat;

namespace PMRC.API.Controllers
{
    [Route("api/wechat")]
    [ApiController]
    public class WechatController : ControllerBase
    {
        private readonly ILogger<WechatController> _logger;
        private readonly IHubContext<ChatHub> _hubContext;
        public WechatController(
            ILogger<WechatController> logger,
            IHubContext<ChatHub> hubContext
            )
        {
            _logger = logger;
            _hubContext = hubContext;
        }

        [HttpGet("callback")]
        public async Task<IActionResult> CallbackAsync(string code, string state)
        {
            try
            {
                var httpContextAccessor = new HttpContextAccessor();
                var responseBody = await WeChatHelpr.GetAccessToken("wx2162cbc289d6bc2a", "d0712c626e9fcfde2ab2a0dbd0ee2ecd", code);
                _logger.LogDebug("callback WeChat Token:{0}", responseBody);
                // 解析JSON响应
                var accessTokenResponse =JsonHelper.Deserialize<AccessTokenResponse>(responseBody);
                //var token = GenerateToken(weChatToken);               
                //var connectionId = HttpContext.Connection.Id;
                await _hubContext.Clients.Client(state).SendAsync("tokenChannel", new
                {

                });
                return Ok();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw;
            }
        }
    }
}
